package com.gismore.parser.excel.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gismore.parser.excel.config.vo.TemplateColumn;
import com.gismore.parser.excel.config.vo.TemplateSheet;
import com.google.common.collect.Lists;
import com.google.common.reflect.Reflection;
import lombok.extern.log4j.Log4j2;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.Converter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.logging.log4j.util.ReflectionUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

@Log4j2
class Converters {

	public static class DevModeConverter implements Converter<Boolean>{

		@Override
		public Boolean convert(Method method, String input) {
			return input.equalsIgnoreCase("dev");
		}
	}

    public static class ExcelTemplateConverter implements Converter<TemplateSheet>{
		@Override
		public TemplateSheet convert(Method method, String sheet) {
			log.debug(sheet);
			TemplateSheet ret = new TemplateSheet();
			List<String> indexList = Lists.newArrayList("sheet","row_begin_inclusive","row_end_inclusive");
			List<String> columnList = Arrays.stream(sheet.split(",")).filter(r->r.contains(":")).collect(toList());

			columnList.stream()
					.filter(r->indexList.stream().anyMatch(s->r.startsWith(s)))
					.forEach(keyValue->{
						String key = StringUtils.substringBefore(keyValue,":");
						Integer value = NumberUtils.toInt(StringUtils.substringAfter(keyValue,":"));
						switch (key){
							case "sheet":
								ret.setSheetIndex(value);
								break;
							case "row_begin_inclusive":
								ret.setRowBeginInclusive(value);
								break;
							case "row_end_inclusive":
								ret.setRowEndInclusive(value);
								break;
						}
					});
			List<TemplateColumn> columns = Lists.newArrayList();
			ret.setColumns(columns);
			columnList.stream()
					.filter(r->indexList.stream().noneMatch(s->r.startsWith(s)))
					.forEach(keyValue->{
						String key = StringUtils.substringBefore(keyValue,":");
						Integer value = NumberUtils.toInt(StringUtils.substringAfter(keyValue,":"));
						TemplateColumn templateColumn = new TemplateColumn(value,key);
						columns.add(templateColumn);
					});
			return ret;
		}
	}
}
